from flask import Blueprint, url_for, render_template, request, current_app,redirect, abort, flash
from app import db
from app.utils.common import login_required
from app.utils.util import create_nonce_str, create_password
from app.models import Tag
from app.constants import PAGE_LIMIT
from app.forms import TagForm
from datetime import datetime

tag_controller = Blueprint("tag", __name__)

@tag_controller.route("/tag/index")
@login_required
def tag():
    page = request.args.get("page", 1, type=int)
    try:
        pagination = Tag.query.order_by(Tag.id.desc()).paginate(page, per_page=PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)
        flash("获取标签失败")

    return render_template('admin/tag/index.html', pagination=pagination)

@tag_controller.route("/tag/add", methods=['GET', 'POST'])
@login_required
def add_tag():
    form = TagForm()
    if request.method == "POST":
        if form.validate_on_submit():
            tagname = form.data.get('tagname')
            try:
                tag = Tag(tagname=tagname)
                db.session.add(tag)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加标签失败")
            return redirect(url_for('tag.tag'))
        
    return render_template("admin/tag/add.html", form=form)

@tag_controller.route("/tag/edit", methods=['GET', 'POST'])
@login_required
def edit_tag():
    id = request.args.get("id", 0)
    try:
        tag = Tag.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("标签不存在")
        return redirect(url_for('tag.tag'))

    form = TagForm()
    if request.method == "POST":
        if form.validate_on_submit():
            tagname = form.data.get('tagname')
            tag.tagname = tagname
            tag.update_time = datetime.now()
            try:
                db.session.add(tag)
                db.session.commit()
                
            except Exception as e:
                current_app.logger.error(e)
                flash("编辑标签失败")
            return redirect(url_for('tag.tag'))
        
    return render_template("admin/tag/edit.html", form=form, tag=tag)

@tag_controller.route("/tag/delete", methods=['GET'])
@login_required
def del_tag():
    id = request.args.get("id", 0, type=int)

    try:
        tag = Tag.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("标签不存在")
        return redirect(url_for('tag.tag'))
    
    if tag:
        try:
            db.session.delete(tag)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            flash("删除标签失败")

    return redirect(url_for('tag.tag'))